incremental typing
Concise and very good explanation
code:python
def foo(x: int):
y: str = x # NG
error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
Explicitly state implicit Any
code:python
import typing
def foo(x: typing.Any):
y: str = x # OK
code:python
def foo(x: int):
y: typing.Any = x # OK
Difference between Any and object
code:python
def foo(x: int):
y: object = x # OK
code:python
def foo(x: object):
y: str = x # NG
error: Incompatible types in assignment (expression has type "object", variable has type "str") [assignment]
Unlike Any, object is just a top type, so trying to assign a value of type object to a value of type str (implicit downcast) is not allowed.
This is normal type behavior.
That Any is a special type that can implicitly perform both upcasts and downcasts.
No guessing the return type.
code:python
def foo(x: int):
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> Any"
This is a different behavior from TypeScript
https://gyazo.com/485b1234b2e40fa0839bf9379e8ddce3
code:python
def foo(x: int) -> int:
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> builtins.int"
It is expected that humans will explicitly state in this way
https://gyazo.com/9ea5aa1dec79c546747debfa28db2621
---
This page is auto-translated from /nishio/漸進的型付け using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.